<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRoute } from "vue-router";
import { UploadFilled, Plus, Delete, Edit } from "@element-plus/icons-vue";
import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import { query_exposure_compliance_asset_group } from "@/api/asset";
import { batchManageAssets } from "@/api/task";
import DynamicForm from "@/components/DynamicForm/index.vue";
import DynamicTable from "@/components/DynamicTable/index.vue";
import type { FormItemConfig } from "@/components/DynamicForm/types";
import type { TableColumn } from "@/components/DynamicTable/types";
import { internetReportTableColumns } from "./hepls";

const route = useRoute();

defineOptions({
  name: "InternetReport",
});

// 搜索表单配置
const searchFormConfig: FormItemConfig[] = [
  {
    key: "asset_ip",
    name: "资产IP地址",
    type: "input",
    placeholder: "请输入资产IP地址",
    col: { span: 4 },
  },
  {
    key: "asset_department",
    name: "资产所属部门",
    type: "input",
    placeholder: "请输入资产所属部门",
    col: { span: 4 },
  },
  {
    key: "asset_name",
    name: "资产名称",
    type: "input",
    placeholder: "请输入资产名称",
    col: { span: 4 },
  },
  {
    key: "asset_type",
    name: "资产类型",
    type: "input",
    placeholder: "请输入资产类型",
    col: { span: 4 },
  },
  {
    key: "service_type",
    name: "服务类型",
    type: "input",
    placeholder: "请输入服务类型",
    col: { span: 4 },
  },
  {
    key: "asset_responsible_person",
    name: "资产负责人",
    type: "input",
    placeholder: "请输入资产负责人",
    col: { span: 4 },
  },
  {
    key: "port_responsible_person",
    name: "端口负责人",
    type: "input",
    placeholder: "请输入端口负责人",
    col: { span: 4 },
  },
  {
    key: "asset_domain",
    name: "资产域名",
    type: "input",
    placeholder: "请输入资产域名",
    col: { span: 4 },
  },
  {
    key: "has_web_interface",
    name: "是否有WEB界面",
    type: "select",
    placeholder: "请选择",
    options: [
      { label: "是", value: "true" },
      { label: "否", value: "false" },
    ],
    col: { span: 4 },
    labelWidth: "120px",
  },
  {
    key: "is_cross_department",
    name: "是否跨部门资产",
    type: "select",
    placeholder: "请选择",
    labelWidth: "120px",
    options: [
      { label: "是", value: "true" },
      { label: "否", value: "false" },
    ],
    col: { span: 4 },
  },
];

// 使用从 helps.ts 导入的表格列配置
const tableColumns = internetReportTableColumns;

// 搜索表单数据
const searchFormData = ref({});

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedRows = ref([]);

// 新增资产表单配置
const addFormConfig: FormItemConfig[] = [
  {
    key: "asset_ip",
    name: "资产IP地址",
    type: "input",
    placeholder: "请输入资产IP地址",
    required: true,
    col: { span: 12 },
  },
  {
    key: "asset_department",
    name: "资产所属部门",
    type: "input",
    placeholder: "请输入资产所属部门",
    required: true,
    col: { span: 12 },
    labelWidth: "120px",
  },
  {
    key: "asset_name",
    name: "资产名称",
    type: "input",
    placeholder: "请输入资产名称",
    col: { span: 12 },
  },
  {
    key: "asset_type",
    name: "资产类型",
    type: "input",
    placeholder: "请输入资产类型",
    col: { span: 12 },
  },
  {
    key: "service_type",
    name: "服务类型",
    type: "input",
    placeholder: "请输入服务类型",
    col: { span: 12 },
  },
  {
    key: "asset_responsible_person",
    name: "资产负责人",
    type: "input",
    placeholder: "请输入资产负责人",
    col: { span: 12 },
    labelWidth: "120px",
  },
  {
    key: "port_responsible_person",
    name: "端口负责人",
    type: "input",
    placeholder: "请输入端口负责人",
    col: { span: 12 },
    labelWidth: "120px",
  },
  {
    key: "asset_domain",
    name: "资产域名",
    type: "input",
    placeholder: "请输入资产域名",
    col: { span: 12 },
  },
  {
    key: "start_port",
    name: "起始端口",
    type: "number",
    placeholder: "请输入起始端口",
    col: { span: 12 },
  },
  {
    key: "end_port",
    name: "结束端口",
    type: "number",
    placeholder: "请输入结束端口",
    col: { span: 12 },
  },
  {
    key: "has_web_interface",
    name: "是否有WEB界面",
    type: "select",
    placeholder: "请选择",
    options: [
      { label: "是", value: true },
      { label: "否", value: false },
    ],
    col: { span: 12 },
    labelWidth: "120px",
  },
  {
    key: "is_cross_department",
    name: "是否跨部门资产",
    type: "select",
    placeholder: "请选择",
    options: [
      { label: "是", value: true },
      { label: "否", value: false },
    ],
    col: { span: 12 },
    labelWidth: "120px",
  },
  {
    key: "web_interface_url",
    name: "WEB界面URL",
    type: "input",
    placeholder: "请输入WEB界面URL",
    col: { span: 24 },
    labelWidth: "120px",
  },
  {
    key: "responsible_contact",
    name: "负责人联系方式",
    type: "input",
    placeholder: "请输入负责人联系方式",
    col: { span: 12 },
    labelWidth: "120px",
  },
  {
    key: "asset_company",
    name: "资产所属公司",
    type: "input",
    placeholder: "请输入资产所属公司",
    col: { span: 12 },
    labelWidth: "120px",
  },
  {
    key: "port_responsible_contact",
    name: "端口负责人电话",
    type: "input",
    placeholder: "请输入端口负责人电话",
    col: { span: 12 },
    labelWidth: "120px",
  },
  {
    key: "port_responsible_department",
    name: "端口负责人部门",
    type: "input",
    placeholder: "请输入端口负责人部门",
    col: { span: 12 },
    labelWidth: "120px",
  },
  {
    key: "asset_record_info",
    name: "资产备案信息",
    type: "input",
    placeholder: "请输入资产备案信息",
    col: { span: 12 },
    labelWidth: "120px",
  },
  {
    key: "asset_device_type",
    name: "资产设备类型",
    type: "input",
    placeholder: "请输入资产设备类型",
    col: { span: 12 },
    labelWidth: "120px",
  },
  {
    key: "device_version",
    name: "设备版本号",
    type: "input",
    placeholder: "请输入设备版本号",
    col: { span: 12 },
  },
  {
    key: "manufacturer_info",
    name: "厂商信息",
    type: "input",
    placeholder: "请输入厂商信息",
    col: { span: 12 },
    labelWidth: "120px",
  },
  {
    key: "operating_system",
    name: "操作系统",
    type: "input",
    placeholder: "请输入操作系统",
    col: { span: 12 },
  },
  {
    key: "os_version",
    name: "操作系统版本",
    type: "input",
    placeholder: "请输入操作系统版本",
    col: { span: 12 },
    labelWidth: "120px",
  },
  {
    key: "software_middleware_info",
    name: "软件/中间件信息",
    type: "textarea",
    placeholder: "请输入软件/中间件信息",
    col: { span: 24 },
    labelWidth: "120px",
  },
  {
    key: "remarks",
    name: "备注",
    type: "textarea",
    placeholder: "请输入备注",
    col: { span: 24 },
  },
];

// 新增资产表单数据
const addFormData = ref({});

// 对话框状态
const showAddDialog = ref(false);
const showEditDialog = ref(false);
const editingAsset = ref(null);

// 上传相关
const showUploadDialog = ref(false);
const fileList = ref([]);
const upData = ref({
  exposure_id: "",
  application_terminal_id: "",
  filename: "",
});
const upUrl = ref("/api/asset/upload_exposure_compliance_asset_group");

// 查询数据
const queryExposureCompliance = async () => {
  try {
    loading.value = true;
    const tp = route.query.tp;
    const params = {
      ...searchFormData.value,
      exposure_id: tp as string,
      page: currentPage.value,
      per_page: pageSize.value,
    };

    const result = await query_exposure_compliance_asset_group(params);

    if (result.code === 2000) {
      tableData.value = result.data;
      total.value = (result as any).total;
    }
  } catch (error) {
    console.error("查询失败:", error);
    message("查询失败", { type: "error" });
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = (data: any) => {
  searchFormData.value = data;
  currentPage.value = 1;
  queryExposureCompliance();
};

// 重置处理
const handleReset = () => {
  searchFormData.value = {};
  currentPage.value = 1;
  queryExposureCompliance();
};

// 分页处理
const handlePageChange = (page: number) => {
  currentPage.value = page;
  queryExposureCompliance();
};

const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
  queryExposureCompliance();
};

// 上传处理
const handleUploadSuccess = (response: any) => {
  if (response.code === 2000) {
    message("上传成功", { type: "success" });
    showUploadDialog.value = false;
    queryExposureCompliance();
  } else {
    message("上传异常", { type: "error" });
  }
};

const beforeUpload = (rawFile: any) => {
  const tp = route.query.tp;
  upData.value = {
    filename: rawFile.name,
    exposure_id: tp as string,
    application_terminal_id: "",
  };
  return true;
};

const uploadError = (error: any) => {
  console.log("上传错误：", error);
  message("上传失败", { type: "error" });
};

// 新增资产
const handleAddAsset = () => {
  addFormData.value = {};
  showAddDialog.value = true;
};

// 编辑资产
const handleEditAsset = (row: any) => {
  editingAsset.value = row;
  addFormData.value = { ...row };
  showEditDialog.value = true;
};

// 删除单个资产
const handleDeleteAsset = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除资产 "${row.asset_name || row.asset_ip}" 吗？`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const result = await batchManageAssets({
      action: "delete",
      asset_model_type: "exposure",
      assets: [{ id: row.id }],
    });

    if (result.code === 2000) {
      message("删除成功", { type: "success" });
      queryExposureCompliance();
    } else {
      message(`删除失败: ${result.message}`, { type: "error" });
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除失败:", error);
      message("删除失败", { type: "error" });
    }
  }
};

// 处理选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    message("请选择要删除的资产", { type: "warning" });
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 条资产吗？`,
      "确认批量删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const assets = selectedRows.value.map((row) => ({ id: row.id }));
    const result = await batchManageAssets({
      action: "delete",
      asset_model_type: "exposure",
      assets,
    });

    if (result.code === 2000) {
      message(`批量删除成功，共删除 ${result.data.success_count} 条记录`, {
        type: "success",
      });
      selectedRows.value = [];
      queryExposureCompliance();
    } else {
      message(`批量删除失败: ${result.message}`, { type: "error" });
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("批量删除失败:", error);
      message("批量删除失败", { type: "error" });
    }
  }
};

// 提交新增/编辑表单
const handleSubmitForm = async (formData: any) => {
  try {
    const action = editingAsset.value ? "update" : "add";
    const assets = editingAsset.value
      ? [{ id: editingAsset.value.id, ...formData }]
      : [formData];

    console.log("提交的表单数据:", formData);
    console.log("API请求参数:", {
      action,
      asset_model_type: "exposure",
      assets,
    });

    const result = await batchManageAssets({
      action,
      asset_model_type: "exposure",
      assets,
    });

    if (result.code === 2000) {
      message(`${editingAsset.value ? "编辑" : "新增"}成功`, {
        type: "success",
      });
      showAddDialog.value = false;
      showEditDialog.value = false;
      editingAsset.value = null;
      addFormData.value = {};
      queryExposureCompliance();
    } else {
      message(
        `${editingAsset.value ? "编辑" : "新增"}失败: ${result.message}`,
        { type: "error" }
      );
    }
  } catch (error) {
    console.error("提交失败:", error);
    message("操作失败", { type: "error" });
  }
};

// 取消表单
const handleCancelForm = () => {
  showAddDialog.value = false;
  showEditDialog.value = false;
  editingAsset.value = null;
  addFormData.value = {};
};

onMounted(() => {
  const tp = route.query.tp;
  upData.value.exposure_id = tp as string;
  queryExposureCompliance();
});

const handleClearAllAssets = () => {
  ElMessageBox.confirm("确定要一键清空吗？", "确认清空", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  });
};
</script>

<template>
  <div class="internet-report-container">
    <!-- 搜索表单 -->
    <el-card>
      <DynamicForm
        :form-config="searchFormConfig"
        :model-value="searchFormData"
        type="search"
        @search="handleSearch"
        @reset="handleReset"
      />
    </el-card>

    <!-- 表格 -->
    <el-card style="margin-top: 20px">
      <DynamicTable
        :data="tableData"
        :columns="tableColumns"
        :loading="loading"
        selection-type="multiple"
        :pagination="{
          currentPage,
          pageSize,
          total,
        }"
        @current-page-change="handlePageChange"
        @size-change="handleSizeChange"
        @selection-change="handleSelectionChange"
      >
        <!-- 工具栏右侧插槽 -->
        <template #toolbar-left>
          <el-button type="success" :icon="Plus" @click="handleAddAsset">
            新增资产
          </el-button>
          <el-button type="danger" :icon="Delete" @click="handleBatchDelete">
            批量删除
          </el-button>
          <el-button
            type="primary"
            :icon="UploadFilled"
            @click="showUploadDialog = true"
          >
            导入互联网报备基表
          </el-button>
          <el-button type="danger" :icon="Delete" @click="handleClearAllAssets">
            一键清空
          </el-button>
        </template>

        <!-- 是否有WEB界面列插槽 -->
        <template #has_web_interface="{ row }">
          <el-tag :type="row.has_web_interface ? 'success' : 'info'">
            {{ row.has_web_interface ? "是" : "否" }}
          </el-tag>
        </template>

        <!-- 是否跨部门资产列插槽 -->
        <template #is_cross_department="{ row }">
          <el-tag :type="row.is_cross_department ? 'warning' : 'info'">
            {{ row.is_cross_department ? "是" : "否" }}
          </el-tag>
        </template>

        <!-- 操作列插槽 -->
        <template #actions="{ row }">
          <!-- <el-button
            type="primary"
            size="small"
            :icon="Edit"
            @click="handleEditAsset(row)"
          >
            编辑
          </el-button> -->
          <el-button
            type="danger"
            size="small"
            :icon="Delete"
            @click="handleDeleteAsset(row)"
          >
            删除
          </el-button>
        </template>
      </DynamicTable>
    </el-card>

    <!-- 新增/编辑资产对话框 -->
    <el-dialog
      v-model="showAddDialog"
      title="新增资产"
      width="80%"
      :show-close="true"
      destroy-on-close
    >
      <div style="height: 68vh; overflow-y: auto; overflow-x: hidden">
        <DynamicForm
          :form-config="addFormConfig"
          :model-value="addFormData"
          type="submit"
          @submit="handleSubmitForm"
          @cancel="handleCancelForm"
        />
      </div>
    </el-dialog>

    <el-dialog
      v-model="showEditDialog"
      title="编辑资产"
      width="80%"
      :show-close="true"
      destroy-on-close
    >
      <DynamicForm
        :form-config="addFormConfig"
        :model-value="addFormData"
        type="submit"
        @submit="handleSubmitForm"
        @cancel="handleCancelForm"
      />
    </el-dialog>

    <!-- 上传对话框 -->
    <el-dialog
      v-model="showUploadDialog"
      title="导入基表"
      width="500px"
      :show-close="true"
      destroy-on-close
    >
      <el-upload
        class="upload-demo"
        drag
        v-model:file-list="fileList"
        :action="upUrl"
        :limit="1"
        :before-upload="beforeUpload"
        :on-success="handleUploadSuccess"
        :on-error="uploadError"
        accept=".xls,.xlsx"
        method="post"
        :with-credentials="true"
        :data="upData"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">拖动文件上传 或者<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">
            请严格按照excel模板文件录入资产并上传
          </div>
        </template>
      </el-upload>

      <template #footer>
        <div>
          <el-button @click="showUploadDialog = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.internet-report-container {
  padding: 20px;
}

.search-container {
  margin-bottom: 20px;
}

.table-container {
  background: white;
  border-radius: 8px;
  padding: 16px;
}
</style>
